// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RenderScheduler.cs" company="XamlNinja">
//   2011 Richard Griffin and Ollie Riches
// </copyright>
// <summary>
//   Schedules the next update.
// </summary>
// <Credits>
//   Original code can be found here http://tombstonehelper.codeplex.com/
//   and additional information here http://msdn.microsoft.com/en-us/library/ff967548(v=vs.92).aspx
// </Credits>
// --------------------------------------------------------------------------------------------------------------------
namespace WP7Contrib.View.Controls.Tombstoner
{
    using System;
    using System.Collections.Generic;
    using System.Windows.Media;

    public static class RenderScheduler
    {
        private static List<Action> workItems;
        
        public static void ScheduleOnNextRender(Action action)
        {
            if (workItems == null)
            {
                workItems = new List<Action>();
                CompositionTarget.Rendering += DoWorkOnRender;
            }

            workItems.Add(action);
        }

        internal static void DoWorkOnRender(object sender, EventArgs args)
        {
            CompositionTarget.Rendering -= DoWorkOnRender;
            var work = workItems;
            workItems = null;

            foreach (var action in work)
            {
                try
                {
                    action();
                }
                catch (Exception)
                {
                }
            }
        }
    }
}